<?php

namespace app\admin\controller;

use app\api\model\ConfigAlipay;
use app\api\model\Withdraw;
use app\api\model\WithdrawMerge;
use app\api\model\YaoqingRecords as Income;
use think\Db;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Pay;
use app\service\WechatTransfer;

class Balance extends Common
{
    public function withdraw(): string
    {
        $date = date('Y-m-d');
    
        $yesterday_start = strtotime('-1 day', strtotime($date));
        $yesterday_date = date('Y-m-d', $yesterday_start);

        $where['t2.delete_time'] = 0;

        $state = input('state') ?: 0;
        $where['t1.state'] = $state;
        
        $paymethod = input('paymethod') ?: 0;
        $where['t1.paymethod'] = $paymethod;

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('withdraw t1')
            ->field('t1.userid, t2.name, t2.phone, t1.paymethod')
            ->join('user t2', 't2.id = t1.userid')
            ->where($where)
            ->group('t1.userid')
            ->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function ($item, $yesterday_date) {
                $date = date('Y-m-d');

                $yesterday_start = strtotime('-1 day', strtotime($date));
                $yesterday_date = date('Y-m-d', $yesterday_start);

                $user_balance = Db::name('user_balance')->where(['user_id' => $item['userid'], 'date' => $yesterday_date])->cache(3600)->find();
                $user_balance_today = Db::name('user_balance')->where(['user_id' => $item['userid'], 'date' => $date])->cache(3600)->find();
                
                $item['score_yesterday'] = $user_balance ? $user_balance['score'] : 0;
                $item['score_today'] = $user_balance_today ? $user_balance_today['score'] : 0;
                
                //$item['income_yesterday'] = $user_balance ? $user_balance['income'] : 0;
                
                if ($user_balance) {
                    $item['income_yesterday'] = $user_balance['income'];
                } else {
                    $item['income_yesterday'] = Db::name('yaoqing_records')
                        ->where(['uid' => $item['userid'], 'type' => 1, 'data' => 0])->whereTime('time', 'yesterday')->cache(3600)->sum('money');
                }

                $item['money'] = Db::name('withdraw')->where(['userid' => $item['userid'], 'state' => ['in', [0,1]]])->whereTime('create_time', 'yesterday')->sum('money');

                $item['warn'] = $item['score_yesterday'] + $item['income_yesterday'] - $item['score_today'] < $item['money'] * 5;

                return $item;
            });

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
    

        $this->assign('start', date('Y-m-d H:i:s', $yesterday_start));
        $yesterday_end = date('Y-m-d H:i:s', ($yesterday_start + 86399));
        $this->assign('end', $yesterday_end);
        
        $this->assign('state', $state);
        $this->assign('paymethod', $paymethod);

        return $this->fetch();
    }

    // public function allWithdraw()
    // {
    //     $user_id = input('user_id');

    //     if (request()->isAjax()) {
    //         $admin = session('admin', '', 'mmjtAdmin');

    //         $admin = Db::name('admin')->find($admin['id']);

    //         if ($admin['type'] != 1) {
    //             return ['err' => '无权限'];
    //         }

    //         if (!isset($admin['safe_pass']) || !$admin['safe_pass']) {

    //             return ['err' => '请先设置管理员操作密码'];
    //         }

    //         $post = input('post.');

    //         if (!isset($post['safe_pass']) || !$post['safe_pass']) {
    //             return ['err' => '请先输入操作密码'];
    //         }

    //         if(!password_verify($post['safe_pass'], $admin['safe_pass'])) {
    //             return ['err' => '操作密码错误'];
    //         }

    //         $state = $post['state'];

    //         $configAlipay = ConfigAlipay::get(['types' => 2, 'is_select' => 1]);
    //         if (!$configAlipay || !$configAlipay['appid'] || !$configAlipay['private_key'] || !$configAlipay['public_key']) {
    //             return ['err' => '请先配置支付宝转账参数'];
    //         }

    //         $user = Db::name('user')->find($user_id);
    //         if (!$user) return ['err' => '用户不存在'];

    //         $withdraw = Db::name('withdraw')->where(['userid' => $user_id, 'state' => 0])->order('id desc')->limit(100)->select();
    //         if (!$withdraw) return ['err' => '未有待审核的提现'];

    //         $WithdrawModel = new Withdraw;
    //         $IncomeModel = new Income;
    //         $current_time = time();

    //         $pass_total = 0;
    //         $pass = [];
    //         $miss = [];
    //         $updates = [];

    //         // 启动事务
    //         Db::startTrans();
    //         try {
    //             if ($state == 2) {
    //                 $content = '提现申请驳回';

    //                 if (isset($post['reason']) && $post['reason']) {
    //                     $content .= '。理由：' . $post['reason'];
    //                 }

    //                 foreach ($withdraw as $key => $item) {
    //                     $miss[$item['id']] = ['total' => $item['price'] + $item['shouxu'], 'msg' => $content];
    //                 }

    //                 $ret = count($miss) . '笔提现已拒绝';
    //             } else {
    //                 foreach ($withdraw as $key => $item) {
    //                     $datas = json_decode($item['data'], true);

    //                     if (!isset($datas['name']) || !$datas['name']) {
    //                         //return ['err' => '未填写提现到款账户姓名'];
    //                         unset($withdraw[$key]);
    //                         $miss[$item['id']] = ['total' => $item['price'] + $item['shouxu'], 'msg' => '未填写提现到款账户姓名'];
    //                         continue;
    //                     }

    //                     if (!isset($datas['account']) || !$datas['account']) {
    //                         //return ['err' => '未填写提现到款账户'];
    //                         unset($withdraw[$key]);
    //                         $miss[$item['id']] = ['total' => $item['price'] + $item['shouxu'], 'msg' => '未填写提现到款账户'];
    //                         continue;
    //                     }

    //                     if ($item['money'] < 1) {
    //                         //return ['err' => '转账金额不能低于1元'];
    //                         unset($withdraw[$key]);
    //                         $miss[$item['id']] = ['total' => $item['price'] + $item['shouxu'], 'msg' => '转账金额不能低于1元'];
    //                         continue;
    //                     }

    //                     $out_biz_no = $item['id'] . uniqid();
    //                     $result = $this->transfer($configAlipay, $out_biz_no, $datas['account'], $item['money'], $datas['name']);

    //                     if ($result['code'] == 200) {
    //                         $response = $result['data'];

    //                         if ($response['code'] == 10000) {
    //                             $datas['order_id'] = $response['order_id'];
    //                             $datas['out_biz_no'] = $response['out_biz_no'];
    //                             $datas['pay_date'] = $response['pay_date'];

    //                             $updates[] = [
    //                                 'id' => $item['id'],
    //                                 'state' => 1,
    //                                 'data' => json_encode($datas, JSON_UNESCAPED_UNICODE),
    //                                 'update_time' => $current_time,
    //                             ];

    //                             $pass_total += $item['money'];
    //                             $pass[] = $item['id'];
    //                         } else {
    //                             //return ['err' => $response['msg']];
    //                             unset($withdraw[$key]);
    //                             $miss[$item['id']] = ['total' => $item['price'] + $item['shouxu'], 'msg' => $response['msg']];
    //                             continue;
    //                         }
    //                     } else if ($result['code'] == 400) {
    //                         $response = $result['msg'];

    //                         if (stripos($response, 'PAYER_BALANCE_NOT_ENOUGH')) {
    //                             //return ['err' => '付款方余额不足'];
    //                             unset($withdraw[$key]);
    //                             $miss[$item['id']] = ['total' => $item['price'] + $item['shouxu'], 'msg' => '付款方余额不足'];
    //                             continue;
    //                         } else if (stripos($response, 'PAYEE_NOT_EXIST')) {
    //                             //return ['err' => '收款方账号不存在'];
    //                             unset($withdraw[$key]);
    //                             $miss[$item['id']] = ['total' => $item['price'] + $item['shouxu'], 'msg' => '收款方账号不存在'];
    //                             continue;
    //                         } else if (stripos($response, 'PAYEE_USER_INFO_ERROR')) {
    //                             //return ['err' => '收款方账号与姓名不匹配'];
    //                             unset($withdraw[$key]);
    //                             $miss[$item['id']] = ['total' => $item['price'] + $item['shouxu'], 'msg' => '收款方账号与姓名不匹配'];
    //                             continue;
    //                         } else {
    //                             //return ['err' => $response];
    //                             unset($withdraw[$key]);
    //                             $miss[$item['id']] = ['total' => $item['price'] + $item['shouxu'], 'msg' => $response];
    //                             continue;
    //                         }
    //                     }

    //                     //usleep(500000);
    //                 }

    //                 // 转账成功后更新提现订单
    //                 if ($updates) {
    //                     $WithdrawModel->saveAll($updates);
    //                 }

    //                 // 转账成功后添加进平台账单
    //                 if ($pass_total) {
    //                     Db::name('platform_balance')->insert([
    //                         'types' => 1,
    //                         'money' => $pass_total,
    //                         'content' => '用户(ID:' . $user_id . ')批量提现',
    //                         'create_time' => $current_time
    //                     ]);
    //                 }

    //                 $ret = count($pass) . '笔成功，' . count($miss) . '笔失败';
    //             }

    //             // 转账失败的自动拒绝
    //             if ($miss) {
    //                 $balance = Db::name('user')->where(['id' => $user_id])->value('score');

    //                 $miss_updates = [];
    //                 $miss_total = 0;
    //                 $miss_income = [];
    //                 foreach ($miss as $key => $item) {
    //                     $balance += $item['total'];

    //                     $miss_updates[] = [
    //                         'id' => $key,
    //                         'state' => 2,
    //                         'reason' => $item['msg'],
    //                         'update_time' => $current_time,
    //                     ];
    //                     $miss_total += $item['total'];

    //                     $miss_income[] = [
    //                         'uid' => $user_id,
    //                         'content' => '提现失败返还。' . $item['msg'],
    //                         'money' => $item['total'],
    //                         'time' => $current_time,
    //                         'type' => 1,
    //                         'balance' => $balance,
    //                     ];
    //                 }

    //                 // 更新提现订单
    //                 if ($miss_updates) {
    //                     $WithdrawModel->saveAll($miss_updates);
    //                 }

    //                 // 添加积分变动记录
    //                 if ($miss_income) {
    //                     $IncomeModel->saveAll($miss_income);
    //                 }

    //                 // 积分账户修改
    //                 if ($miss_total) {
    //                     $miss_total = changefloor($miss_total);
    //                     Db::name('user')->where('id', $user_id)->setInc('score', $miss_total);
    //                 }
    //             }

    //             // 提交事务
    //             Db::commit();
    //         } catch (\Exception $e) {
    //             // 回滚事务
    //             Db::rollback();

    //             return ['err' => $e->getMessage()];
    //         }

    //         $data = ['ret' => $ret];
    //     } else {
    //         if (!$user_id) {
    //             return ['err' => '参数错误'];
    //         }
    //         $data = $this->fetch();
    //     }
    //     return $data;
    // }
    public function allWithdraw()
    {
        $user_id = input('user_id');

        if (request()->isAjax()) {
            $admin = session('admin', '', 'mmjtAdmin');

            $admin = Db::name('admin')->find($admin['id']);

            if ($admin['type'] != 1) {
                return ['err' => '无权限'];
            }

            if (!isset($admin['safe_pass']) || !$admin['safe_pass']) {

                return ['err' => '请先设置管理员操作密码'];
            }

            $post = input('post.');

            if (!isset($post['safe_pass']) || !$post['safe_pass']) {
                return ['err' => '请先输入操作密码'];
            }

            if(!password_verify($post['safe_pass'], $admin['safe_pass'])) {
                return ['err' => '操作密码错误'];
            }

            $state = $post['state'];

            $configAlipay = ConfigAlipay::get(['types' => 2, 'is_select' => 1]);
            if (!$configAlipay || !$configAlipay['appid'] || !$configAlipay['private_key'] || !$configAlipay['public_key']) {
                return ['err' => '请先配置支付宝转账参数'];
            }

            $user = Db::name('user')->find($user_id);
            if (!$user) return ['err' => '用户不存在'];

            $withdraw = Db::name('withdraw_merge')->where(['userid' => $user_id, 'state' => 0])->whereTime('create_time', 'yesterday')->find();
            if (!$withdraw) return ['err' => '昨日未有待审核的提现'];

            $WithdrawModel = new Withdraw;
            $WithdrawMergeModel = new WithdrawMerge;
            $IncomeModel = new Income;
            $current_time = time();

            $pass_total = 0;
            $pass = [];
            $miss = false;
            $updates = [];

            // 启动事务
            Db::startTrans();
            try {
                if ($state == 2) {
                    $content = '提现申请驳回';

                    if (isset($post['reason']) && $post['reason']) {
                        $content .= '。理由：' . $post['reason'];
                    }
                    $miss = true;

                    $ret = '提现已拒绝';
                } else {
                    $datas = json_decode($withdraw['data'], true);

                    if (!isset($datas['name']) || !$datas['name']) {
                        $miss = true;
                        $content = '未填写提现到款账户姓名';
                    }

                    if (!isset($datas['account']) || !$datas['account']) {
                        $miss = true;
                        $content = '未填写提现到款账户';
                    }

                    if ($withdraw['money'] < 1) {
                        $miss = true;
                        $content = '转账金额不能低于1元';
                    }
                    if (!$miss){
                        $out_biz_no = $withdraw['id'] . uniqid();
                        if($withdraw['paymethod'] == 1){
                            $result = $this->transfer($configAlipay, $out_biz_no, $datas['account'], $withdraw['money'], $datas['name']);
                            
                            if ($result['code'] == 200) {
                                $response = $result['data'];

                                if ($response['code'] == 10000) {
                                    $datas['order_id'] = $response['order_id'];
                                    $datas['out_biz_no'] = $response['out_biz_no'];
                                    $datas['pay_date'] = $response['pay_date'];

                                    $updates = [
                                        'id' => $withdraw['id'],
                                        'state' => 1,
                                        'data' => json_encode($datas, JSON_UNESCAPED_UNICODE),
                                        'update_time' => $current_time,
                                    ];


                                    // 转账成功后更新提现订单
                                    $WithdrawMergeModel->update($updates);

                                    $withdraw_ids = explode(',',$withdraw['withdraw_ids']);
                                    $passSourse = [];
                                    foreach ($withdraw_ids as $value) {
                                        $updates['id'] = $value;
                                        array_push($passSourse, $updates);
                                    }

                                    // 更新提现订单
                                    $WithdrawModel->saveAll($passSourse);

                                    // 转账成功后添加进平台账单
                                    Db::name('platform_balance')->insert([
                                        'types' => 1,
                                        'money' => $withdraw['money'],
                                        'content' => '用户(ID:' . $user_id . ')批量提现',
                                        'create_time' => $current_time
                                    ]);

                                    $ret = '提现成功';
                                } else {
                                    $ret = '提现失败';
                                    $miss = true;
                                    $content = $response['msg'];
                                }
                            } else if ($result['code'] == 400) {
                                $response = $result['msg'];

                                if (stripos($response, 'PAYER_BALANCE_NOT_ENOUGH')) {
                                    $miss = true;
                                    $content = '付款方余额不足';
                                } else if (stripos($response, 'PAYEE_NOT_EXIST')) {
                                    $miss = true;
                                    $content = '收款方账号不存在';
                                } else if (stripos($response, 'PAYEE_USER_INFO_ERROR')) {
                                    $miss = true;
                                    $content = '收款方账号与姓名不匹配';
                                } else {
                                    $miss = true;
                                    $content = $response;
                                }
                            }
                        } else{
                            $wechat = new WechatTransfer;
                            // var_dump($datas['name']);exit;
                            $WechatOfTransfer = !isset($datas['type']) || $datas['type'] == 0;
                            if($WechatOfTransfer){
                                $result = $wechat->transfer($datas['account'], $out_biz_no, $withdraw['money'], $datas['name'], $user_id . ' '.getenv('APP_NAME'), $user_id . ' '.getenv('APP_NAME'));
                            }else{
                                $result = $wechat->sendPacket($withdraw['money'], $out_biz_no, $datas['account'], $user_id . ' '.getenv('APP_NAME'));
                            }
                            if(isset($result['code']) || (isset($result['result_code']) && $result['result_code'] != 'SUCCESS')){
                                $content = $WechatOfTransfer ? $result['message'] : $result['return_msg'];
                                $miss = true;
                            }else{
                                $batchesStatus = false;
                                if($WechatOfTransfer){
                                    $batchesStatus = $wechat->batchesStatus($result['batch_id']);
                                }
                                if($batchesStatus){
                                    $content = $batchesStatus;
                                    $miss = true;
                                }else{
                                    $datas['order_id'] = $WechatOfTransfer ? $result['batch_id'] : $result['send_listid'];
                                    $datas['out_biz_no'] = $WechatOfTransfer ? $result['out_batch_no'] : $result['mch_billno'];
                                    $datas['pay_date'] = $WechatOfTransfer ? $result['create_time'] : time();

                                    $updates = [
                                        'id' => $withdraw['id'],
                                        'state' => 1,
                                        'data' => json_encode($datas, JSON_UNESCAPED_UNICODE),
                                        'update_time' => $current_time,
                                    ];


                                    // 转账成功后更新提现订单
                                    $WithdrawMergeModel->update($updates);

                                    $withdraw_ids = explode(',',$withdraw['withdraw_ids']);
                                    $passSourse = [];
                                    foreach ($withdraw_ids as $value) {
                                        $updates['id'] = $value;
                                        array_push($passSourse, $updates);
                                    }

                                    // 更新提现订单
                                    $WithdrawModel->saveAll($passSourse);

                                    // 转账成功后添加进平台账单
                                    Db::name('platform_balance')->insert([
                                        'types' => 1,
                                        'money' => $withdraw['money'],
                                        'content' => '用户(ID:' . $user_id . ')批量提现',
                                        'create_time' => $current_time
                                    ]);

                                    $ret = '提现成功';
                                }

                            }
                        }
                    }

                }

                // 转账失败的自动拒绝
                if ($miss) {
                    $balance = Db::name('user')->where(['id' => $user_id])->value('score');

                    $balance = $balance + $withdraw['price'] + $withdraw['shouxu'];

                    $miss_updates = [
                        'id' => $withdraw['id'],
                        'state' => 2,
                        'reason' => $content,
                        'update_time' => $current_time,
                    ];

                    $miss_income = [
                        'uid' => $user_id,
                        'content' => '提现失败返还。' . $content,
                        'money' => $withdraw['price'] + $withdraw['shouxu'],
                        'time' => $current_time,
                        'type' => 1,
                        'balance' => $balance,
                    ];

                    $WithdrawMergeModel->update($miss_updates);

                    $withdraw_ids = explode(',',$withdraw['withdraw_ids']);
                    $missSourse = [];
                    foreach ($withdraw_ids as $value) {
                        $miss_updates['id'] = $value;
                        array_push($missSourse, $miss_updates);
                    }

                    // 更新提现订单
                    $WithdrawModel->saveAll($missSourse);

                    // 添加积分变动记录
                    $IncomeModel->insert($miss_income);

                    // 积分账户修改
                    $miss_total = changefloor($withdraw['price'] + $withdraw['shouxu']);
                    Db::name('user')->where('id', $user_id)->setInc('score', $miss_total);
                    
                    $ret = $content;
                }

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                return ['err' => $e->getMessage()];
            }

            $data = ['ret' => $ret];
        } else {
            if (!$user_id) {
                return ['err' => '参数错误'];
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function transfer($configs, $out_biz_no, $payee_account, $amount, $payee_real_name)
    {
        $config = [
            'alipay' => [
                'app_id' => $configs['appid'],
                'ali_public_key' => $configs['public_key'],
                'private_key' => $configs['private_key'],
            ],
        ];

        $config_biz = [
            'out_biz_no' => $out_biz_no,                // 订单号
            'payee_type' => 'ALIPAY_LOGONID',           // 收款方账户类型(ALIPAY_LOGONID | ALIPAY_USERID)
            'payee_account' => $payee_account,          // 收款方账户
            'amount' => $amount,                        // 转账金额
            //'payer_show_name' => '未寒',               // 付款方姓名
            'payee_real_name' => $payee_real_name,      // 收款方真实姓名
            'remark' => getenv('APP_NAME') . '平台提现',  // 转账备注
        ];

        $pay = new Pay($config);

        try {
            $response = $pay->driver('alipay')->gateway('transfer')->pay($config_biz);

            return ['code' => 200, 'data' => $response];
        } catch (GatewayException $e) {
            return ['code' => 400, 'msg' => $e->getMessage()];
        }
    }


    public function tixianreject()
    {
        $admin = session('admin', '', 'mmjtAdmin');
        $admin = Db::name('admin')->find($admin['id']);

        $ids = input('ids');
        $reason = input('reason');


        if ($admin['type'] != 1) {
            return ['err' => '无权限'];
        }

        $WithdrawModel = new Withdraw;
        $WithdrawMergeModel = new WithdrawMerge;
        $IncomeModel = new Income;
        $current_time = time();

        $withdraws = Db::name('withdraw')->where(['id' => ['in', $ids], 'state'=>0])->select();


        if(sizeof($withdraws) == 0){
            return ['err' => '操作错误'];
        }

        $backcount = 0;
        $backscore = 0;
        $backshouxu = 0;
        $decprice = 0;
        $wids = array_column($withdraws,'id');

        foreach($withdraws as $key => $value){
            $miss_updates[] = [
                'id' => $value['id'],
                'state' => 2,
                'reason' => $reason,
                'update_time' => $current_time,
            ];
            $backscore += $value['price'];
            $backshouxu += $value['shouxu'];
            $decprice += $value['money'];
        }
        $backcount = $backscore + $backshouxu;

        $balance = Db::name('user')->where(['id' => $withdraws[0]['userid']])->value('score');

        $balance = $balance + $backcount;

        $miss_income = [
            'uid' => $withdraws[0]['userid'],
            'content' => '提现失败返还。' . $reason,
            'money' => $backcount,
            'time' => $current_time,
            'type' => 1,
            'balance' => $balance,
        ];

        $withdrawmerge = Db::name('withdraw_merge')->where(['userid' => ['in', $withdraws[0]['userid']], 'state'=>0, 'price' => ['>', 0]])->order('id','desc')->find();

        if($withdrawmerge){
            $withdraw_ids = explode(',',$withdrawmerge['withdraw_ids']);
            $new_ids = [];
            $dec_ids = [];
            foreach ($withdraw_ids as $value) {
                if(in_array($value, $wids)){
                    $dec_ids[] = $value;
                }else{
                    $new_ids[] = $value;
                }
            }
            if(sizeof($dec_ids) != sizeof($wids)){
                return ['err' => '拒绝异常'];
            }
            $WithdrawMergeModel->where(['id'=>$withdrawmerge['id']])->update([
                'price'=>$withdrawmerge['price'] - $backscore,
                'shouxu'=>$withdrawmerge['shouxu'] - $backshouxu,
                'money'=>$withdrawmerge['money'] - $decprice,
                'withdraw_ids'=>implode(',', $new_ids)
            ]);
        }



        // 更新提现订单
        $WithdrawModel->saveAll($miss_updates);

        // 添加积分变动记录
        $IncomeModel->insert($miss_income);

        Db::name('user')->where('id', $withdraws[0]['userid'])->setInc('score', $backcount);
                    


        return ['ret' => '成功拒绝'.(isset($dec_ids) ? sizeof($dec_ids) : sizeof($miss_updates)).'笔提现'];
    }
}
